package cn.tj212.xiaoyin.common.storage;

import org.springframework.util.Assert;

import java.util.Arrays;

public class FileTypeHelper {

    /**
     * 将字节数组的前28个数转换成魔数与FileType作比较
     * @param buff
     * @return
     */
    public static FileType getType(byte[] buff) {
        Assert.isTrue(buff!=null&&buff.length>28);
        byte[] bytes=Arrays.copyOfRange(buff,0,28);
        String magic=bytesToHex(bytes);

        for (FileType type:FileType.values()
             ) {
            if (magic.startsWith(type.getValue()))
                return type;
        }
        return null;
    }

    private static String bytesToHex(byte[] src) {
        StringBuilder stringBuilder=new StringBuilder();
        if (src==null||src.length<=0) return null;

        for (int i = 0; i < src.length; i++) {
            int v=src[i]&0xFF;
            String hv=Integer.toHexString(v);
            if(hv.length()<2){
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString().toUpperCase();
    }

    /**
     * 判断是否为图片，是图片则返回true，否则false
     * @param buff
     * @return
     */
    public static boolean isImage(byte[] buff){
        FileType type=getType(buff);
        return FileType.JEPG.equals(type)||FileType.PNG.equals(type);
    }


}
